package com.ipan.weixin.msg.general;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;

/**
 * 关注/取消关注事件
 * 
 * 用户扫描带场景值二维码时，可能推送以下两种事件： 
 * 1 如果用户还未关注公众号，则用户可以关注公众号，关注后微信会将带场景值关注事件推送给开发者。
 * 2 如果用户已经关注公众号，则微信会将带场景值扫描事件推送给开发者。 
 * @author iPan
 * @version 2013-12-23
 */
public class SubscribeEventMsg extends EventMsg {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = -798477013433041043L;
	
	/** 事件KEY值，qrscene_为前缀，后面为二维码的参数值 */
	protected String eventKey;

	/** 二维码的ticket，可用来换取二维码图片 */
	protected String ticket;
	
	public SubscribeEventMsg() {
		super(TransportType.RECEIVE);
	}
	
	public SubscribeEventMsg(Document doc) {
		this();
		fromXml(doc);
	}
	
	public String getEventKey() {
		return eventKey;
	}

	public void setEventKey(String eventKey) {
		this.eventKey = eventKey;
	}

	public String getTicket() {
		return ticket;
	}

	public void setTicket(String ticket) {
		this.ticket = ticket;
	}

	@Override
	public void fromXml(Document doc) {
		if (doc == null) {
			return ;
		}
		
		super.fromXml(doc);
		Element root = doc.getRootElement();
		this.eventKey = root.elementTextTrim(EL_EVENT_KEY);
		this.ticket = root.elementTextTrim(EL_TICKET);
	}
	
	@Override
	public String toXml(boolean nonEmpty) {
		StringBuilder buf = new StringBuilder("<xml>");
		buf.append(super.toXml(nonEmpty));
		buf.append(wrapElementHead(EL_MSG_TYPE)).append(TYPE_EVENT).append(wrapElementEnd(EL_MSG_TYPE));
		if (nonEmpty) {
			if (StringUtils.isNotEmpty(this.eventKey)) {
				buf.append(wrapElementHead(EL_EVENT_KEY)).append(this.eventKey).append(wrapElementEnd(EL_EVENT_KEY));
			}
			if (StringUtils.isNotEmpty(this.ticket)) {
				buf.append(wrapElementHead(EL_TICKET)).append(this.ticket).append(wrapElementEnd(EL_TICKET));
			}
		} else {
			buf.append(wrapElementHead(EL_EVENT_KEY)).append(getStringValue(this.eventKey)).append(wrapElementEnd(EL_EVENT_KEY));
			buf.append(wrapElementHead(EL_TICKET)).append(getStringValue(this.ticket)).append(wrapElementEnd(EL_TICKET));
		}
		return buf.append("</xml>").toString();
	}

}

/*
接收：
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[FromUser]]></FromUserName>
<CreateTime>123456789</CreateTime>
<MsgType><![CDATA[event]]></MsgType>
<Event><![CDATA[subscribe]]></Event>
</xml>
*/